<template>
    <j-modal :title="title" :width="width" :visible="visible" :confirmLoading="confirmLoading" :keyboard="false"
        :forceRender="true" switchFullscreen @cancel="handleCancel" style="top: 20px; height: 95%">
        <template slot="footer">
            <a-button @click="handleCancel">取消</a-button>
            <!-- <a-button v-if="checkFlag && isCanCheck" :loading="confirmLoading" @click="handleOkAndCheck">保存并审核</a-button> -->
            <a-button :loading="confirmLoading" @click="handleOk">保存</a-button>
            <a-button type="primary" :loading="confirmLoading" @click="handleOkPay">保存并审核</a-button>
            <!--发起多级审核-->
            <a-button v-if="!checkFlag" @click="handleWorkflow()" type="primary">提交流程</a-button>
        </template>
        <a-spin :spinning="confirmLoading">
            <a-form :form="form">
                <a-row class="form-row" :gutter="24">
                    <a-col :lg="6" :md="12" :sm="24">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="付款会员">
                            <a-select placeholder="选择付款会员" v-decorator="['organId', validatorRules.organId]"
                                :dropdownMatchSelectWidth="false" showSearch optionFilterProp="children">
                                <a-select-option v-for="(item, index) in retailList" :key="index" :value="item.id">
                                    {{ item.supplier }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :lg="6" :md="12" :sm="24">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="单据日期">
                            <j-date v-decorator="['billTime', validatorRules.billTime]" :disabled="!!model.id"
                                :show-time="true" />
                        </a-form-item>
                    </a-col>
                    <a-col :lg="6" :md="12" :sm="24">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="单据编号">
                            <a-input placeholder="请输入单据编号" v-decorator.trim="['billNo']" :readOnly="true" />
                        </a-form-item>
                    </a-col>
                    <a-col :lg="6" :md="12" :sm="24">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="财务人员">
                            <a-select placeholder="选择财务人员" v-decorator="['handsPersonId']"
                                :dropdownMatchSelectWidth="false" showSearch optionFilterProp="children">
                                <div slot="dropdownRender" slot-scope="menu">
                                    <v-nodes :vnodes="menu" />
                                    <a-divider style="margin: 4px 0" />
                                    <div v-if="isTenant" style="padding: 4px 8px; cursor: pointer"
                                        @mousedown="(e) => e.preventDefault()" @click="addPerson">
                                        <a-icon type="plus" /> 新增经手人
                                    </div>
                                </div>
                                <a-select-option v-for="(item, index) in personList" :key="index" :value="item.id">
                                    {{ item.name }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                </a-row>
                <j-editable-table :ref="refKeys[0]" :loading="accountTable.loading" :columns="accountTable.columns"
                    :dataSource="accountTable.dataSource" :minWidth="minWidth" :maxHeight="300" :rowNumber="false"
                    :rowSelection="true" :actionButton="true" @valueChange="onValueChange" />
                <a-row class="form-row" :gutter="24">
                    <a-col :lg="24" :md="24" :sm="24">
                        <a-form-item :labelCol="labelCol" :wrapperCol="{ xs: { span: 24 }, sm: { span: 24 } }" label="">
                            <a-textarea :rows="2" placeholder="请输入备注" v-decorator="['remark']"
                                style="margin-top: 8px" />
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row class="form-row" :gutter="24">
                    <a-col :lg="6" :md="12" :sm="24">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="合计金额">
                            <a-input placeholder="请输入合计收款" v-decorator.trim="['totalPrice']" :readOnly="true" />
                        </a-form-item>
                    </a-col>
                    <a-col :lg="6" :md="12" :sm="24">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="收款金额">
                            <a-input placeholder="请输入收款金额" v-decorator.trim="['changeAmount']" :readOnly="true" />
                        </a-form-item>
                    </a-col>
                    <a-col :lg="6" :md="12" :sm="24">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="收款类型" data-step="3"
                            data-title="收款类型"
                            data-intro="收款类型可以有现付和预付款两种类型，当选择了会员之后，如果该会员有预付款，在此处会显示具体预付款的金额，而且系统会优先默认选中预付款">
                            <a-select placeholder="请选择付款类型" v-decorator="['payType']" :dropdownMatchSelectWidth="false"
                                @change="onChangePayType">
                                <a-select-option v-for="(item, index) in payTypeList" :key="index" :value="item.value">
                                    {{ item.text }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :lg="6" :md="12" :sm="24"> </a-col>
                </a-row>
                <a-row class="form-row" :gutter="24">
                    <a-col :lg="6" :md="12" :sm="24">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="附件">
                            <j-upload v-model="fileList" bizPath="financial"></j-upload>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </a-spin>

        <a-modal :visible="payModal" title="支付" @ok="handleCancelPay" @cancel="handleCancelPay" :maskClosable="false">
            <template slot="footer">
                <a-button v-show="payState == 1" type="danger" key="back" @click="handleCancelPay"> 取消支付 </a-button>
            </template>
            <div style="font-size: 32px; text-align: center; color: #18af18">支付金额：{{ model.changeAmount }}</div>
            <div v-show="payState == 1 || payState == 2" style="line-height: 60px; text-align: center">
                请出示付款码（微信/支付宝），扫码支付
            </div>
            <div style="width: 100%; text-align: center; position: relative">
                <img @click="focusInput" v-show="payState == 1 || payState == 2" src="../../../assets/payImg.png"
                    style="width: 200px; height: 200px" alt="" />
                <div v-show="payState == 2" class="pay-model">支付中，请勿关闭</div>
                <img v-show="payState == 3" @click="focusInput" src="../../../assets/paySuccess.png"
                    style="width: 200px; height: 200px" alt="" />
            </div>
            <a-input style="z-index: -1" ref="ainput" @pressEnter="payAuthCode" placeholder="请输入条码"
                v-model="payForm.authCode" />
        </a-modal>

        <person-modal ref="personModalForm" @ok="personModalFormOk"></person-modal>
        <workflow-iframe ref="modalWorkflow"></workflow-iframe>
    </j-modal>
</template>
<script>
import pick from 'lodash.pick'
import PersonModal from '../../system/modules/PersonModal'
import WorkflowIframe from '@/components/tools/WorkflowIframe'
import { FormTypes, VALIDATE_NO_PASSED, validateFormAndTables } from '@/utils/JEditableTableUtil'
import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
import { FinancialModalMixin } from '../mixins/FinancialModalMixin'
import JUpload from '@/components/jeecg/JUpload'
import JDate from '@/components/jeecg/JDate'
import { httpAction } from '@/api/manage'
import { microPayYFK, ysPay } from '@/api/api'
export default {
    name: 'AdvanceInModal',
    mixins: [JEditableTableMixin, FinancialModalMixin],
    components: {
        PersonModal,
        WorkflowIframe,
        JUpload,
        JDate,
        VNodes: {
            functional: true,
            render: (h, ctx) => ctx.props.vnodes,
        },
    },
    data() {
        return {
            title: '操作',
            width: '1600px',
            moreStatus: false,
            // 新增时子表默认添加几行空数据
            addDefaultRowNum: 1,
            visible: false,
            prefixNo: 'SYF',
            model: {},
            fileList: [],
            labelCol: {
                xs: { span: 24 },
                sm: { span: 8 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
            },
            refKeys: ['accountDataTable'],
            activeKey: 'accountDataTable',
            accountTable: {
                loading: false,
                dataSource: [],
                columns: [
                    {
                        title: '账户名称',
                        key: 'accountId',
                        width: '20%',
                        type: FormTypes.select,
                        placeholder: '请选择${title}',
                        options: [],
                        allowSearch: true,
                        validateRules: [{ required: true, message: '${title}不能为空' }],
                    },
                    {
                        title: '金额',
                        key: 'eachAmount',
                        width: '10%',
                        type: FormTypes.inputNumber,
                        statistics: true,
                        placeholder: '请选择${title}',
                        validateRules: [{ required: true, message: '${title}不能为空' }],
                    },
                    {
                        title: '备注',
                        key: 'remark',
                        width: '30%',
                        type: FormTypes.input,
                        placeholder: '请选择${title}',
                    },
                ],
            },
            confirmLoading: false,
            validatorRules: {
                organId: {
                    rules: [{ required: true, message: '请选择付款会员!' }],
                },
                billTime: {
                    rules: [{ required: true, message: '请选择单据日期!' }],
                },
            },
            url: {
                add: '/accountHead/addAccountHeadAndDetail',
                edit: '/accountHead/updateAccountHeadAndDetail',
                detailList: '/accountItem/getDetailList',
            },
            payModal: false,
            payState: 1,
            payForm: {
                authCode: '',
                outTradeNo: '',
            },
            orderPayType: '扫码支付',
            payTypeList: [
                // { value: '扫码支付', text: '扫码支付' },
                { value: '刷卡支付', text: '刷卡支付' },
                { value: '现付', text: '现付' },
            ],
        }
    },
    created() {},
    methods: {
        handleOkPay() {
            this.billStatus = '1'
            this.payForm.authCode = ''
            this.payState = 1
            if (this.orderPayType == '扫码支付') {
                if (
                    this.form.getFieldValue('changeAmount') == '0' ||
                    this.form.getFieldValue('changeAmount') == '0.00'
                ) {
                    this.$message.error('扫码支付，收款金额不能为0！！！')
                    return
                }
            }
            this.validateFields()
        },
        /** 触发表单验证 */
        validateFields() {
            /** 触发表单验证 */
            this.getAllTable()
                .then((tables) => {
                    /** 一次性验证主表和所有的次表 */
                    return validateFormAndTables(this.form, tables)
                })
                .then((allValues) => {
                    if (typeof this.classifyIntoFormData !== 'function') {
                        throw this.throwNotFunction('classifyIntoFormData')
                    }
                    let formData = this.classifyIntoFormData(allValues)
                    // 发起请求
                    this.payForm.outTradeNo = this.model.billNo
                    return this.request(formData)
                })
                .catch((e) => {
                    if (e.error === VALIDATE_NO_PASSED) {
                        // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                        this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
                    } else {
                        console.error(e)
                    }
                })
        },

        /** 发起请求，自动判断是执行新增还是修改操作 */
        request(formData) {
            let url = this.url.add,
                method = 'post'
            if (this.model.id) {
                url = this.url.edit
                method = 'put'
            }
            this.confirmLoading = true
            httpAction(url, formData, method)
                .then((res) => {
                    if (res.code === 200) {
                        if (this.orderPayType == '扫码支付' && this.billStatus == '1') {
                            this.$emit('ok')
                            this.confirmLoading = false
                            this.payModal = true
                            this.focusInput()
                        } else {
                            this.$emit('ok')
                            this.confirmLoading = false
                            this.close()
                        }
                    } else {
                        this.$message.error(res.data.message)
                        this.confirmLoading = false
                    }
                })
                .finally(() => {})
        },
        handleCancelPay() {
            this.payModal = false
            this.confirmLoading = false
            this.close()
        },
        focusInput() {
            this.$nextTick(() => {
                this.$refs.ainput.focus()
            })
        },
        onChangePayType(e) {
            this.orderPayType = e
        },
        payAuthCode() {
            this.payState = 2
            microPayYFK(this.payForm).then((res) => {
                if (res.code == '12500002') {
                    this.payForm.authCode = ''
                    this.$message.error(res.data.msg)
                    this.payState = 1
                } else if (res.data.trade_status == 'TRADE_SUCCESS') {
                    // 支付成功
                    this.payState = 3
                    setTimeout(() => {
                        this.payModal = false
                        this.close()
                    }, 1200)
                } else if (res.data.trade_status == 'TRADE_PROCESS') {
                    // 支付中
                    this.tradeNo = res.data.trade_no
                    setTimeout(() => {
                        this.cyclePay()
                    }, 1000)
                } else {
                    // 支付异常
                    this.$message.error(res.data.msg)
                    setTimeout(() => {
                        this.payModal = false
                        this.close()
                    }, 1000)
                }
            })
        },

        cyclePay() {
            ysPay({ tradeNo: this.tradeNo }).then((res) => {
                if (res.data.trade_status == 'TRADE_SUCCESS') {
                    // 支付成功
                    this.payState = 3
                    setTimeout(() => {
                        this.payModal = false
                        this.close()
                    }, 1200)
                } else if (res.data.trade_status == 'TRADE_PROCESS') {
                    // 支付中
                    setTimeout(() => {
                        this.cyclePay()
                    }, 1000)
                } else {
                    // 支付异常
                    this.$message.error(res.data.msg)
                    setTimeout(() => {
                        this.payModal = false
                        this.close()
                    }, 1000)
                }
            })
        },
        //调用完edit()方法之后会自动调用此方法
        editAfter() {
            this.billStatus = '0'
            if (this.action === 'add') {
                this.addInit(this.prefixNo)
                this.fileList = []
                this.$nextTick(() => {
                    // 2024 10 28 修改
                    // this.orderPayType = '扫码支付'
                    this.orderPayType = '刷卡支付'
                    // this.form.setFieldsValue({ payType: '扫码支付' })
                    this.form.setFieldsValue({ payType: '刷卡支付' })
                })
            } else {
                this.model.billTime = this.model.billTimeStr
                this.orderPayType = this.model.payType
                this.$nextTick(() => {
                    this.form.setFieldsValue(
                        pick(
                            this.model,
                            'organId',
                            'handsPersonId',
                            'billTime',
                            'billNo',
                            'remark',
                            'totalPrice',
                            'changeAmount',
                            'payType'
                        )
                    )
                })
                this.fileList = this.model.fileName
                // 加载子表数据
                let params = {
                    headerId: this.model.id,
                }
                let url = this.readOnly ? this.url.detailList : this.url.detailList
                this.requestSubTableData(url, params, this.accountTable)
            }
            this.initSystemConfig()
            this.initRetail()
            this.initPerson()
            this.initDetailAccount()
        },
        //提交单据时整理成formData
        classifyIntoFormData(allValues) {
            let totalPrice = 0
            let billMain = Object.assign(this.model, allValues.formValue)
            let detailArr = allValues.tablesValue[0].values
            billMain.type = '收预付款'
            for (let item of detailArr) {
                totalPrice += item.eachAmount - 0
            }
            billMain.totalPrice = totalPrice
            if (this.fileList && this.fileList.length > 0) {
                billMain.fileName = this.fileList
            }
            if (this.model.id) {
                billMain.id = this.model.id
            }
            billMain.status = this.billStatus
            return {
                info: JSON.stringify(billMain),
                rows: JSON.stringify(detailArr),
            }
        },
    },
}
</script>
<style scoped>
</style>